package com.hd.appcommon.dd.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiV2DepartmentGetRequest;
import com.dingtalk.api.request.OapiV2DepartmentListsubidRequest;
import com.dingtalk.api.request.OapiV2UserGetRequest;
import com.dingtalk.api.request.OapiV2UserListRequest;
import com.dingtalk.api.response.OapiV2DepartmentGetResponse;
import com.dingtalk.api.response.OapiV2DepartmentListsubidResponse;
import com.dingtalk.api.response.OapiV2UserGetResponse;
import com.dingtalk.api.response.OapiV2UserListResponse;
import com.hd.appcommon.constant.URLConstant;
import com.hd.appcommon.dd.api.ddentity.DdUserInfo;
import com.hd.appcommon.entity.Dept;
import com.hd.appcommon.entity.User;
import com.hd.appcommon.service.UserService;
import com.hd.appcommon.utils.AccessTokenUtil;
import com.hd.hdxgddcommon.utils.CollectionUtils;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author: hzp
 * @date: 2022/3/24
 * @description:
 */
@Slf4j
@Component
public class UserinfoAPI {
    @Autowired
    UserService userService;
//    /**
//     * 获取用户json信息 https://open.dingtalk.com/document/orgapp-server/query-user-details
//     *
//     * @param staffId dd用户id
//     * @return 用户json
//     */
//    public static JSONObject getUserInfoFromDD(String staffId) {
//        String token = AccessTokenUtil.getToken();
//
//        JSONObject userJson = new JSONObject();
//        try {
//            DingTalkClient client = new DefaultDingTalkClient(URLConstant.URL_USERV2_GET);
//            OapiV2UserGetRequest req = new OapiV2UserGetRequest();
//            req.setUserid(staffId);
//            OapiV2UserGetResponse rsp = client.execute(req, token);
//            userJson = JSONObject.parseObject(rsp.getBody());
//        } catch (ApiException e) {
//            e.printStackTrace();
//        }
//        return userJson.getJSONObject("result");
//    }

    public void getAllInfo() throws ApiException {

        long start = System.currentTimeMillis();
        log.info("get student task start at " + start);

        String access_token = AccessTokenUtil.getToken();
        // 层序遍历, 一层层获取 ,放入queue  , id pid name
        // 根据队列里的数据获取详细信息 dept_id , parent_id,  name, group_contain_sub_dept , org_dept_owner , dept_manager_userid_list
        Queue<Long> queue = new LinkedList<>();
        // 放入整个学院的初始部门
        queue.offer(1L);
        while (!queue.isEmpty()) {
            int size = queue.size();
            // 一次一层
            for (int i = 0; i < size; i++) {
                Long node = queue.poll();
                // 钉钉查询这个部门里的所有人, 插入数据库 ,需要反复
                boolean sign = true;
                long cur = 0L;
                while (sign) {
                    sign = getDeptUserInfo(access_token, node, cur, "student");
                    cur += 100;
                }
                // 把一个node 对应的部门的所有的子部门全部放入queque 中, 查询子部门
                List<Long> deptSons = getDeptSons(access_token, node);
                for (Long l : deptSons) {
                    queue.offer(l);
                }
            }
        }
        long end = System.currentTimeMillis();

        log.info("get student task end at " + end);
        log.info("get student task cost " + (end - start));
    }
    /**
     * {
     * "errcode": 0,
     * "errmsg":"ok",
     * "result": {
     * "dept_id_list": [
     * 379xxxx95,
     * 411xxxx76,
     * 399xxxx96,
     * 400xxxx83,
     * 404xxxx47
     * ]
     * },
     * "request_id": "169dfniaazqb4"
     * }
     */
    public List<Long> getDeptSons(String access_token, Long deptId) throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsubid");
        OapiV2DepartmentListsubidRequest req = new OapiV2DepartmentListsubidRequest();
        req.setDeptId(deptId);
        OapiV2DepartmentListsubidResponse rsp = client.execute(req, access_token);
        JSONObject jsonObject = JSONObject.parseObject(rsp.getBody());
        // 判断 code 是否是正确

        Object result = jsonObject.get("result");
        String r = result.toString();
        JSONObject jsonObject1 = JSONObject.parseObject(r);
        // 返回Long 数组
        return JSONArray.parseArray(JSON.toJSONString(jsonObject1.get("dept_id_list")), Long.class);
    }
    public boolean getDeptUserInfo(String access_token, Long deptId, Long cursor, String flag) throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/list");
        OapiV2UserListRequest req = new OapiV2UserListRequest();
        req.setDeptId(deptId);
        // 一次同步一百个
        req.setCursor(cursor);
        req.setSize(cursor + 100);
        req.setOrderField("modify_desc");
        req.setContainAccessLimit(false);
        req.setLanguage("zh_CN");
        OapiV2UserListResponse rsp = client.execute(req, access_token);
//        System.out.println(rsp.getBody());
        // 返回还有没有
        JSONObject jsonObject = JSONObject.parseObject(rsp.getBody());
        Object result = jsonObject.get("result");
        String r;
        if(null!=result) r = result.toString();else  return false;
        JSONObject jsonObject1 = JSONObject.parseObject(r);
        // 拿出数据去更新
        List<DdUserInfo> list = JSONArray.parseArray(JSON.toJSONString(jsonObject1.get("list")), DdUserInfo.class);
        // 新增或者更新 根据手机号
        // 存储手机号, 姓名 ,dept_id_list, userId, job_number(工号)
        List<User> updateUserList = new ArrayList<>();
        for (DdUserInfo ddUserInfo : list) {
            //不论学生还是老师，都是根据学/工号进行更新
            User user = userService.getOne(new QueryWrapper<User>().eq("job_number",ddUserInfo.getJob_number()));
            if(null==user||null==user.getId()) continue;
            String phone = ddUserInfo.getMobile();
            if(!StringUtils.isBlank(phone)&&!phone.trim().equals(""))
                user.setPhone(phone);
            StringBuffer dept_id_list = new StringBuffer();
            List<Long> list0 = ddUserInfo.getDept_id_list();
            boolean flag0 = false;
            for (Object s:list0){
                if(flag0){
                    dept_id_list.append("-");
                }
                flag0 = true;
                dept_id_list.append(s.toString());
            }
            user.setDdDeptId(dept_id_list.toString());
            user.setDdid(ddUserInfo.getUserid());
            updateUserList.add(user);
        }
        if(null!=updateUserList&&updateUserList.size()>0)
        userService.updateBatchById(updateUserList);
        return (boolean) jsonObject1.get("has_more");
    }
}
